package com.dsx.exception;

import com.dsx.commons.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * @author dsx
 * @date 2021/3/31 8:59
 * @since JDK1.8
 */
@Slf4j
//全局异常处理
@RestControllerAdvice    
public class GlobalExceptionHandle {
    
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public Result handler1(ShiroException e){
        log.error("ShiroException----->"+e);
        return Result.fail(401,e.getMessage(),null);
    }
    
    /**
     * 处理Assert的异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) throws IOException {
        log.error("Assert异常:-------------->{}",e.getMessage());
        return Result.fail(e.getMessage());
    }
    /**
     * @Validated 校验错误异常处理
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = BindException.class)
    public Result handler(BindException e) throws IOException {
        log.error("实体校验异常:-------------->",e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.fail(objectError.getDefaultMessage());//{"code": 300,"msg": "邮箱格式不正确", "data": null}
//        return Result.fail(e.getMessage());  //返回的错误太长了，用上面方法返回我们在实体类注解中设置的错误信息
        //返回的是"code": 300,
        //    "msg": "org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'user' on field 'email': rejected value [xxx]; codes [Email.user.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@6fe43302,.*]; default message [邮箱格式不正确]",
        //    "data": null
    }
    
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(RuntimeException.class)
    public Result handler2(RuntimeException e){
        log.error("RuntimeException----->"+e);
        return Result.fail(e.getMessage());
    }
}
